package cn.blue.exception;
import cn.blue.result.JSONResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {
    //系统异常处理
    @ExceptionHandler(Exception.class)
    public JSONResult exceptionHandler(Exception e){
        e.printStackTrace();
        return JSONResult.error("请求失败,请重试!");
    }
    //自定义异常处理
    @ExceptionHandler(GlobalException.class)
    public JSONResult globalExceptionHandler(GlobalException globalException){
        globalException.printStackTrace();
        return JSONResult.error(globalException);
    }
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JSONResult methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException m){
        m.printStackTrace();
        StringBuilder sb = new StringBuilder();
        //取出异常信息
        m.getBindingResult().getAllErrors().forEach(error->{
            sb.append(error.getDefaultMessage());
        });
        return JSONResult.error(sb.toString(),GlobalExceptionCodeEnum.PHONE_IS_FORMAT_ERROR.getErrCode());
    }

}
